{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 41,
   "id": "bcbe92b2",
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import pandas as pd\n",
    "\n",
    "import requests\n",
    "import datetime\n",
    "import hashlib\n",
    "import base64\n",
    "import hmac\n",
    "import json"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 44,
   "id": "5a37a886",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 讯飞机器翻译平台 API\n",
    "class get_result(object):\n",
    "    def __init__(self,host):\n",
    "        # 应用ID（到控制台获取）\n",
    "        self.APPID = \"\"\n",
    "        # 接口APISercet（到控制台机器翻译服务页面获取）\n",
    "        self.Secret = \"\"\n",
    "        # 接口APIKey（到控制台机器翻译服务页面获取）\n",
    "        self.APIKey= \"\"\n",
    "        \n",
    "        \n",
    "        # 以下为POST请求\n",
    "        self.Host = host\n",
    "        self.RequestUri = \"/v2/ots\"\n",
    "        # 设置url\n",
    "        # print(host)\n",
    "        self.url=\"https://\"+host+self.RequestUri\n",
    "        self.HttpMethod = \"POST\"\n",
    "        self.Algorithm = \"hmac-sha256\"\n",
    "        self.HttpProto = \"HTTP/1.1\"\n",
    "\n",
    "        # 设置当前时间\n",
    "        curTime_utc = datetime.datetime.utcnow()\n",
    "        self.Date = self.httpdate(curTime_utc)\n",
    "        # 设置业务参数\n",
    "        # 语种列表参数值请参照接口文档：https://www.xfyun.cn/doc/nlp/niutrans/API.html\n",
    "        self.Text=\"How old are you\"\n",
    "        self.BusinessArgs={\n",
    "                \"from\": \"en\",\n",
    "                \"to\": \"ja\",\n",
    "            }\n",
    "\n",
    "    def hashlib_256(self, res):\n",
    "        m = hashlib.sha256(bytes(res.encode(encoding='utf-8'))).digest()\n",
    "        result = \"SHA-256=\" + base64.b64encode(m).decode(encoding='utf-8')\n",
    "        return result\n",
    "\n",
    "    def httpdate(self, dt):\n",
    "        \"\"\"\n",
    "        Return a string representation of a date according to RFC 1123\n",
    "        (HTTP/1.1).\n",
    "\n",
    "        The supplied date must be in UTC.\n",
    "\n",
    "        \"\"\"\n",
    "        weekday = [\"Mon\", \"Tue\", \"Wed\", \"Thu\", \"Fri\", \"Sat\", \"Sun\"][dt.weekday()]\n",
    "        month = [\"Jan\", \"Feb\", \"Mar\", \"Apr\", \"May\", \"Jun\", \"Jul\", \"Aug\", \"Sep\",\n",
    "                 \"Oct\", \"Nov\", \"Dec\"][dt.month - 1]\n",
    "        return \"%s, %02d %s %04d %02d:%02d:%02d GMT\" % (weekday, dt.day, month,\n",
    "                                                        dt.year, dt.hour, dt.minute, dt.second)\n",
    "\n",
    "    def generateSignature(self, digest):\n",
    "        signatureStr = \"host: \" + self.Host + \"\\n\"\n",
    "        signatureStr += \"date: \" + self.Date + \"\\n\"\n",
    "        signatureStr += self.HttpMethod + \" \" + self.RequestUri \\\n",
    "                        + \" \" + self.HttpProto + \"\\n\"\n",
    "        signatureStr += \"digest: \" + digest\n",
    "        signature = hmac.new(bytes(self.Secret.encode(encoding='utf-8')),\n",
    "                             bytes(signatureStr.encode(encoding='utf-8')),\n",
    "                             digestmod=hashlib.sha256).digest()\n",
    "        result = base64.b64encode(signature)\n",
    "        return result.decode(encoding='utf-8')\n",
    "\n",
    "    def init_header(self, data):\n",
    "        digest = self.hashlib_256(data)\n",
    "        #print(digest)\n",
    "        sign = self.generateSignature(digest)\n",
    "        authHeader = 'api_key=\"%s\", algorithm=\"%s\", ' \\\n",
    "                     'headers=\"host date request-line digest\", ' \\\n",
    "                     'signature=\"%s\"' \\\n",
    "                     % (self.APIKey, self.Algorithm, sign)\n",
    "        #print(authHeader)\n",
    "        headers = {\n",
    "            \"Content-Type\": \"application/json\",\n",
    "            \"Accept\": \"application/json\",\n",
    "            \"Method\": \"POST\",\n",
    "            \"Host\": self.Host,\n",
    "            \"Date\": self.Date,\n",
    "            \"Digest\": digest,\n",
    "            \"Authorization\": authHeader\n",
    "        }\n",
    "        return headers\n",
    "\n",
    "    def get_body(self):\n",
    "        content = str(base64.b64encode(self.Text.encode('utf-8')), 'utf-8')\n",
    "        postdata = {\n",
    "            \"common\": {\"app_id\": self.APPID},\n",
    "            \"business\": self.BusinessArgs,\n",
    "            \"data\": {\n",
    "                \"text\": content,\n",
    "            }\n",
    "        }\n",
    "        body = json.dumps(postdata)\n",
    "        #print(body)\n",
    "        return body\n",
    "\n",
    "    def call_url(self):\n",
    "        if self.APPID == '' or self.APIKey == '' or self.Secret == '':\n",
    "            print('Appid 或APIKey 或APISecret 为空！请打开demo代码，填写相关信息。')\n",
    "        else:\n",
    "            code = 0\n",
    "            body=self.get_body()\n",
    "            headers=self.init_header(body)\n",
    "            #print(self.url)\n",
    "            response = requests.post(self.url, data=body, headers=headers,timeout=8)\n",
    "            status_code = response.status_code\n",
    "            #print(response.content)\n",
    "            if status_code!=200:\n",
    "                # 鉴权失败\n",
    "                print(\"Http请求失败，状态码：\" + str(status_code) + \"，错误信息：\" + response.text)\n",
    "                print(\"请根据错误信息检查代码，接口文档：https://www.xfyun.cn/doc/nlp/niutrans/API.html\")\n",
    "            else:\n",
    "                # 鉴权成功\n",
    "                respData = json.loads(response.text)\n",
    "                # print(respData)\n",
    "                # 以下仅用于调试\n",
    "                code = str(respData[\"code\"])\n",
    "                if code!='0':\n",
    "                    print(\"请前往https://www.xfyun.cn/document/error-code?code=\" + code + \"查询解决办法\")\n",
    "                return respData"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 45,
   "id": "1a6d9279",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 机器翻译封装方法\n",
    "def translate(text='你好世界', source='cn', target='uy'):\n",
    "    ##示例:  host=\"ntrans.xfyun.cn\"域名形式\n",
    "    host = \"ntrans.xfyun.cn\"\n",
    "    #初始化类\n",
    "    gClass=get_result(host)\n",
    "    gClass.Text = text\n",
    "    gClass.BusinessArgs['from'] = source\n",
    "    gClass.BusinessArgs['to'] = target\n",
    "    result = gClass.call_url()\n",
    "    return result['data']['result']['trans_result']['dst']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 46,
   "id": "af12b196",
   "metadata": {},
   "outputs": [],
   "source": [
    "cat_uy_df = pd.read_csv('../datasets/商品分类关键词_维语.csv', encoding='utf-8', header=0)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 47,
   "id": "5a8bf38e",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>keywords_uy</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>ماللار تۈرى</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>ئۆي جابدۇقلىرى</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>شەخسىي ساغلاملىق</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>كىيىم-زىبۇزىننەت</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>ئېلېكتىر سايمانلىرى</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "           keywords_uy\n",
       "0          ماللار تۈرى\n",
       "1       ئۆي جابدۇقلىرى\n",
       "2     شەخسىي ساغلاملىق\n",
       "3     كىيىم-زىبۇزىننەت\n",
       "4  ئېلېكتىر سايمانلىرى"
      ]
     },
     "execution_count": 47,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "cat_uy_df.head()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 57,
   "id": "66b791fc",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 生成关键词列表\n",
    "# keywords_uy = [word[0] for _, word in cat_uy_df.iterrows()]\n",
    "keywords_uy = cat_uy_df['keywords_uy'].tolist()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 58,
   "id": "e749d04c",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['ماللار تۈرى',\n",
       " 'ئۆي جابدۇقلىرى',\n",
       " 'شەخسىي ساغلاملىق',\n",
       " 'كىيىم-زىبۇزىننەت',\n",
       " 'ئېلېكتىر سايمانلىرى']"
      ]
     },
     "execution_count": 58,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "keywords_uy[:5]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 59,
   "id": "552df447",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 生成翻译关键词列表\n",
    "keywords_uy2cn = [translate(text=tx, source='uy', target='cn') for tx in keywords_uy]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 60,
   "id": "c91d85a1",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['货品', '家具', '个人健康', '服饰', '电器']"
      ]
     },
     "execution_count": 60,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "keywords_uy2cn[:5]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 64,
   "id": "ddc10737",
   "metadata": {},
   "outputs": [],
   "source": [
    "keywords_uy2cn_df = pd.DataFrame({'keywords_uy2cn':keywords_uy2cn})"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 65,
   "id": "ecbd7afe",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>keywords_uy2cn</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>货品</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>家具</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>个人健康</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>服饰</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>电器</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "  keywords_uy2cn\n",
       "0             货品\n",
       "1             家具\n",
       "2           个人健康\n",
       "3             服饰\n",
       "4             电器"
      ]
     },
     "execution_count": 65,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "keywords_uy2cn_df.head()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 67,
   "id": "38dc6e89",
   "metadata": {},
   "outputs": [],
   "source": [
    "keywords_uy2cn_df.to_csv('../datasets/商品分类关键词_维语转汉语.csv', encoding='utf-8-sig', header=0, index = False)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 69,
   "id": "49018f29",
   "metadata": {},
   "outputs": [],
   "source": [
    "cat_uy_df.to_csv('../datasets/商品分类关键词_维语.csv', encoding='utf-8-sig', header=0, index = False)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "50fbd80a",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.8"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
